package com.reliable.service.controller;

import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.service.domain.ReliableDouArea;
import com.reliable.service.service.IReliableDouAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 地区Controller
 *
 * @author ruoyi
 * @date 2025-07-09
 */
@RestController
@RequestMapping("/reliable/area")
@Api(value = "地区控制器", tags = {"地区管理"})
public class ReliableDouAreaController {

    @Autowired
    private IReliableDouAreaService reliableDouAreaService;



    /**
     * 获取地区级联树
     */
    @ApiOperation("获取地区级联树")
    @PostMapping("/tree")
    public AjaxResult getAreaTree() {
        List<ReliableDouArea> areaList = reliableDouAreaService.list();
        if (CollUtil.isEmpty(areaList)) {
            return AjaxResult.success(CollUtil.newArrayList());
        }

        // 转换为 TreeNode
        List<TreeNode<Long>> nodeList = areaList.stream().map(area -> {
            TreeNode<Long> node = new TreeNode<>();
            node.setId(area.getAreaId());
            node.setParentId(ObjectUtil.defaultIfNull(area.getParentId(), 0L));
            node.setName(area.getName());
            node.setExtra(BeanUtil.beanToMap(area));
            return node;
        }).collect(Collectors.toList());

        // 构建树
        List<Tree<Long>> treeList = TreeUtil.build(nodeList, 0L);
        return AjaxResult.success(treeList);
    }



}
